package band.wukong.practice.springboot.spring4.mvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wukong(wukonggg@139.com)
 */
public class HiIntercepter extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(HiIntercepter.class);

    private static final String REQ_START_TIME = "requestStartTime";
    private static final String REQ_HANDLING_TIME = "requestHandlingTime";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute(REQ_START_TIME, System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (Long) request.getAttribute(REQ_START_TIME);
        long endTime = System.currentTimeMillis();

        long time = endTime - startTime;
        logger.debug("本次请求时间为 {} 毫秒", time);
        System.out.printf("本次请求时间为 %d 毫秒\n", time);

        request.setAttribute(REQ_HANDLING_TIME, time);
        request.removeAttribute(REQ_START_TIME);
    }


}
